import axios from "axios";
import {useTokenStore} from "@/stores/tokenStore.js";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";
import {useUserStore} from "@/stores/user.js";
//创建axios 的对象
const service = axios.create({
    baseURL: import.meta.env.VITE_SERVER_ADDR
});
//请求拦截器
service.interceptors.request.use(req =>{
    //携带token
    const tokenStore = useTokenStore();

    if (tokenStore.tokenStr){
        req.headers.token = tokenStore.tokenStr
    }
    return req;
},error => {

})

//响应拦截器
service.interceptors.response.use(resp =>{
    //刷新token
    const token = resp.headers.token;
    if (token){
        const tokenStore = useTokenStore();
        tokenStore.updateToken(token);
    }
    return resp.data;
},error =>{
    //403 销毁token
    if (error.status == 403) {
        ElMessage.error({
            message: '令牌错误，请重新登录',
            duration: 1200,
            onClose: ()=> {
                const tokenStore = useTokenStore();
                tokenStore.$reset();
                const uerStore = useUserStore();
                uerStore.$reset();
                let currentPath = router.currentRoute.value.path;
                if (currentPath.startsWith("/admin")){
                    router.push("/admin/login");
                }else {
                    router.push("/user/login");
                }
            }
        })
    }
})

export default service;